package cn.loan.controller;

import cn.loan.config.key.SessionKey;
import cn.loan.entity.User;
import cn.loan.service.IdCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

/**
 * @Author: 毛苏宇
 * @Description: You can do it!
 * @Date: Create in 22:40 2019/4/20
 */
@Controller
@RequestMapping("/card")
public class IdCardController {

    @Autowired
    private IdCardService idCardService;

    @RequestMapping("/idcard")
    public String idCard(HttpSession session) {
        final User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        //身份证是否存在
        final boolean exist = idCardService.findIdCardExist(user);
        if (exist) {
            return "redirect:/loan/auth";
        } else {
            return "/idcard";
        }
    }

    @PostMapping("/upload/idcard")
    public String uploadIdCard(MultipartFile positive, MultipartFile reverse_side, HttpSession session) {
        try {
            final User user = (User) session.getAttribute(SessionKey.SESSION_USER);
            final int userId = user.getUser_id();
            //得到照片大小
            final double size1 = positive.getSize() / 1024.00 / 1024.00;
            final double size2 = reverse_side.getSize() / 1024.00 / 1024.00;
            //如果照片大小超过10M则不能继续
            System.out.println(size1 + "\t" + size2);
            if (size1 < 10 && size2 < 10) {
                //身份证正面后缀名
                String suffix1 = positive.getOriginalFilename().substring(positive.getOriginalFilename().lastIndexOf('.')).toLowerCase();
                //身份证反面后缀名
                String suffix2 = reverse_side.getOriginalFilename().substring(reverse_side.getOriginalFilename().lastIndexOf('.')).toLowerCase();
                if ((".jpg".equals(suffix1) || ".png".equals(suffix1) || ".jpeg".equals(suffix1)) && (".jpg".equals(suffix2) || ".png".equals(suffix2) || ".jpeg".equals(suffix2))) {
                    //插入用户提交的身份证照片
                    final boolean status = idCardService.add(positive, reverse_side, user);
                    if (status) {
                        return "redirect:/loan/auth";
                    } else {
                        return "redirect:/card/idcard";
                    }
                } else {
                    return "redirect:/card/idcard";
                }
            } else {
                return "redirect:/card/idcard";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/card/idcard";
        }
    }

}
